<template>
  <!--弹出窗-->
  <modal ref="modal_1"
         :title="title"
         :isCloseConfirm="this.editable"
         :fullscreen="this.fullscreen"
         top="3%"
         width="50%"
         :close-on-click-modal="true"
         @modalOpened="opened"
         @modalClose="closed">


    <avue-form ref="form"
               :option="option"
               v-model="form"
               @submit="onSubmit" >

      <template #materialNo v-if="this.editable">
        <el-autocomplete
            style="width: 100%;"
            v-model="form.materialNo"
            :fetch-suggestions="queryMaterialNo"
            placeholder="请输入物料编号"
            :trigger-on-focus="false"
            @select="selectMaterialNo"
            :fit-input-width="true"
        ></el-autocomplete>
      </template>

      <template #materialName v-if="this.editable">
        <el-input v-model="form.materialName" readonly placeholder="请选择物料名称" @click="selectMaterialName" />
      </template>

      <template #programName v-if="this.editable">
        <el-input v-model="form.programName" readonly placeholder="请选择品牌" @click="selectProgramName" />
      </template>
    </avue-form>

    <!--底部按钮块, 默认只有"取消"按钮-->
    <template #footerButton>
      <el-button type="primary" v-if="(permission.sales_price_add || permission.sales_price_edit) && editable"
                 :loading="btnLoading" @click="this.$refs.form.submit()">保 存
      </el-button>
      <el-button @click="$refs.modal_1.handleClose()">关闭</el-button>
    </template>
    <select-material  ref="selectMaterial"  @success="setSelectMaterial"/>
    <select-program  ref="selectProgram"  @success="setSelectProgram"/>
  </modal>
</template>

<script>
import { getList, getDetail, add, update, remove } from "@/api/anwise/sales/sales_price";
import {getDetail as getDetailMaterial,remoteListByAll as remoteListMaterial} from "@/api/anwise/material/material";
import {getDetail as getDetailProgram}  from "@/api/anwise/material/customer_group";
import selectMaterial from './select_material_single.vue';
import selectProgram from './select_program.vue';
import { mapGetters } from "vuex";
import {Pattern} from "@/utils/validate.js";
import {dateFormat} from "@/utils/date";

export default {
  components: {
    selectMaterial,
    selectProgram
  },
  data() {
    return {
      title:"销售单价信息",
      emits: ["success"],
      editable: false,
      isCloseConfirm: false,
      fullscreen: false,
      btnLoading: false,
      box:false,
      form: {},
      query: {},
      props: {
        label: 'nodeName',
        value: 'id',
      },
      proData:{},
      workListData:[],
      defaultChecks:[],
      workList:[],
      workListNodeId:[],
      loading: true,
      deptId:"",
      option: {
        height: 'auto',
        calcHeight: 30,
        labelWidth: 150,
        menuWidth: 120,
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "物料编号",
            prop: "materialNo",
            type: "input",
            width:130,
            rules: [{
              required: true,
              message: "请输入物料编号",
              trigger: "blur"
            }],
          },
          {
            label: "物料名称",
            prop: "materialName",
            type: "input",
            search: true,
            overHidden: true,
            sortable: true,
            width:130,
            rules: [{
              required: true,
              message: "请输入物料名称",
              trigger: "blur"
            }],
          },
          {
            label: "品牌",
            prop: "programName",
            type: "input",
            search: true,
            overHidden: true,
            sortable: true,
            width:130,
            rules: [{
              required: true,
              message: "请输入品牌",
              trigger: "blur"
            }],
          },
          {
            label: "品牌分组",
            prop: "programGroup",
            type: "input",
            disabled: true,
            search: true,
            overHidden: true,
            sortable: true,
            width:130
          },
          {
            label: "客户条码",
            prop: "barCode",
            type: "input",
            disabled:true,
            search: true,
            overHidden: true,
            sortable: true,
            width:130,
            // rules: [{
            //     required: true,
            //     message: "请输入客户条码",
            //     trigger: "blur"
            // }],
          },
          {
            label: '贸易条款',
            prop: 'tradeTerms',
            type: 'select',
            filterable:true,
            dicUrl: '/api/blade-system/dict-biz/dictionary?code=trade_terms',
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
            value:"ex-work(SZ)",
            dataType: 'string',
            search: true,
            rules: [
              {
                required: true,
                message: '请选择贸易条款',
                trigger: 'blur',
              },
            ],
          },
          {
            label: "单价",
            prop: "price",
            type: "number",
            controls:false,
            min:0,
            rules: [
              {
                required: true,
                message: '请输入单价',
                trigger: 'blur',
              },
            ],
            search: true,
            overHidden: true,
            sortable: true,
            width:130
          },
          {
            label: "币别",
            prop: "rmb",
            disabled:true,
            type: "select",
            filterable: true,
            overHidden: true,
            sortable: true,
            width:120,
            dicUrl: '/api/blade-system/dict-biz/dictionary?code=rmb',
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
            dataType: 'string',
          },
          {
            label: "生效日期",
            prop: "activeDate",
            type: "date",
            format: "YYYY年MM月DD日",
            valueFormat: "YYYY-MM-DD",
            search: true,
            overHidden: true,
            sortable: true,
            width:130,
            rules: [{
              required: true,
              message: "请选择生效日期",
              trigger: "blur"
            }],
          },
          {
            label: "备注",
            prop: "remark",
            type: "textarea",
            overHidden: true,
            sortable: true,
            span: 24,
          },
          {
            label: "审核人员",
            prop: "approver",
            type: "input",
            overHidden: true,
            sortable: true,
            width:130,
            disabled:true,
            rules: [{
              required: false,
              message: "请输入审核人员",
              trigger: "blur"
            }],
          },
          {
            label: "审核日期",
            prop: "approverDate",
            type: "date",
            valueFormat: 'YYYY-MM-DD',
            format:'YYYY-MM-DD',
            overHidden: true,
            sortable: true,
            width:130,
            disabled:true,
            rules: [{
              required: false,
              message: "请选择审核日期",
              trigger: "blur"
            }],
          }
        ]
      },
      data: [],
      ifullscreen:false
    };
  },
  computed: {
    ...mapGetters(["permission","userInfo"]),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.purchase_price_add, false),
        viewBtn: this.validData(this.permission.purchase_price_view, false),
        delBtn: this.validData(this.permission.purchase_price_delete, false),
        editBtn: this.validData(this.permission.purchase_price_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  mounted() {
  },
  methods: {
    handleFullScreen() {
      this.ifullscreen = !this.ifullscreen;
    },
    renderContent(h, {data}){
      return h(
          'span',
          {
            style: {
              color: '#626AEF',
            },
          },
          data.nodeName+" [<"+data.parentNo+">"+data.parentName+"]"
      )
    },
    open(){
      this.workListNodeId.forEach(res=>{
        this.$refs.treeMenu.setChecked(res, true);
      })
    },
    menuCheck(data, isChecked) {
      if (isChecked) {
        if (data.parentId) {
          this.setParentCheck(data.id)
        }
      } else {
        this.setChildUncheck(data.id)
      }
    },
    setChildUncheck(id) {
      const node = this.$refs.treeMenu.getNode(id);
      if (node.data.children) {
        node.data.children.forEach(item => {
          this.$refs.treeMenu.setChecked(item.id, false);
          this.setChildUncheck(item.id)
        })
      }
    },
    setParentCheck(id) {
      const node = this.$refs.treeMenu.getNode(id);
      if (node.data.parentId) {
        this.$refs.treeMenu.setChecked(node.data.parentId, true);
        this.setParentCheck(node.data.parentId)
      }
    },
    selectProgramName(){
      this.$refs.selectProgram.showSelect();
    },
    setSelectProgram(data){
      console.log(data)
      getDetailProgram(data.id).then(res => {
        if (res.data.success) {
          let data = res.data.data;
          this.form.programName = data.programName;
          this.form.programGroup = data.programGroup;
          this.form.rmb = data.rmb;
        }
      }).catch(err => {
        this.$message({
          type: "error",
          message: "选择品牌时发生异常！"
        });
      })
    },
    selectMaterialName() {
      this.$refs.selectMaterial.showSelect();
    },
    setSelectMaterial(data){
      getDetailMaterial(data.id).then(res => {
        if (res.data.success) {
          let data = res.data.data;
          this.form.materialNo = data.materialNo;
          this.form.materialId = data.id;
          this.form.materialName = data.materialName;
          this.form.barCode = data.barCode;
        }
      }).catch(err => {
        this.$message({
          type: "error",
          message: "选择物料时发生异常！"
        });
      })
    },
    queryMaterialNo(val,cb){
      this.form.materialType = "";
      this.form.barCode = "";
      this.form.materialName = "";
      this.form.workList = "";

      remoteListMaterial(val).then(res => {
        if (res.data.success) {
          let materialList = [];
          res.data.data.forEach(item => {
            materialList.push({
              value:item.materialNo +" - "+item.materialName,
              materialType: item.type,
              barCode: item.barCode,
              materialNo: item.materialNo,
              materialName: item.materialName,
              specification: item.specification,
              id: item.id
            });
          })
          cb(materialList);
        }
      })
    },
    selectMaterialNo(item){
      console.log(item);
      this.form.barCode = item.barCode;
      this.form.materialNo = item.materialNo;
      this.form.materialName = item.materialName;
      this.form.materialId = item.id;
    },
    onSubmit(form, done) {
      this.btnLoading = true;
      let now = new Date();
      if(form.activeDate<dateFormat(now,"yyyy-MM-dd")){
        this.$message({
          type: "error",
          message: "生效日期不能小于当前日期！"
        });
        done();
        this.btnLoading = false;
        return;
      }
      update(form).then(res => {
        if (res.data.success) {
          this.$message({
            type: "success",
            message: res.msg || "保存成功!"
          });
          setTimeout(() => {
            this.btnLoading = false;
            done();
            this.$refs.modal_1.hide();
          }, 1000)
        } else {
          this.$message({
            type: "error",
            message: res.msg || "保存失败!"
          });
        }
      }).catch(err => {
        done();
        this.btnLoading = false;
      })
    },
    show(option) {
      this.title = option.title;
      this.type = option.type;
      if (option.id) {
        setTimeout(() => {
          getDetail(option.id).then(res => {
            if (res.data.success) {
              if(this.type === 'copy'){
                res.data.data.id="";
                res.data.data.activeDate = "";
                res.data.data.approver = "";
                res.data.data.approverDate = "";
              }
              this.form = res.data.data;
            }
          })
        }, 500);
      } else {
        this.form = {
        }
      }
      this.option.detail = this.type === "view";
      this.editable = this.type !== "view";
      this.$refs.modal_1.show();
    },
    rowSave(row, done, loading) {
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
    },
    beforeOpen(done, type) {
      if (["edit", "view","copy"].includes(type)) {
        getDetail(this.form.id).then(res => {
          if(type === 'copy'){
            res.data.data.id="";
            res.data.data.taxExclusivePrice = "";
            res.data.data.activeDate = "";
          }
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    opened() {
      console.log("opened")
    },
    closed() {
      this.$emit("success");
    }
  }
};
</script>

<style></style>
